<?php

/**
 * 用户系统消息模型
 */

namespace app\api\model;


use PDOStatement;
use think\Collection;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\Model;

class MessageUserSystem extends Model {

    /**
     * 获取最新消息
     * @param $user_id
     * @return array
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getNew($user_id, $column) {
        $data = Db::name("message_user_system")->where("user_id", $user_id)->field($column)->order('itime', 'desc')->select();
        if (!empty($data)) {
            return $data[0];
        } else {
            return [];
        }

    }

    /**
     * 未读
     * @param $user_id
     * @return float|string
     */
    public static function getNotread($user_id) {
        return Db::name("message_user_system")->where("user_id", $user_id)->where("is_read", 0)->count();
    }

    /**
     * 系统所有信息
     * @param $params
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getAllsystemMessage($params) {
        //阅读
        db("message_user_system")->where('user_id', $params['user_id'])->update(['is_read' => 1]);
        $data = Db::name("message_user_system")
            ->where("user_id", $params['user_id'])
            ->order('itime', 'desc')
            ->field('title,content,itime,pic,link_title,link,type')
            ->select();
        foreach ($data as $k => $datum) {
            $data[$k]['itime'] = date('Y-m-d H:i:s', $data[$k]['itime']);
            $data[$k]['avatar'] = 'https://dss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3315452533,3675827540&fm=26&gp=0.jpg';
        }
        return $data;
    }

    /**
     * 阅读
     * @param $params
     * @throws Exception
     * @throws PDOException
     */
    public static function read($params) {
        db("message_user_system")->where('user_id', $params['user_id'])->update(['is_read' => 1]);
    }

}
